package servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException;


import cmput391.src.queries.*;
import entities.User;

/**
 * Servlet implementation class AddUser
 */
@WebServlet("/AddUser")
public class AddUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> messages = new HashMap<String, String>();
		request.setAttribute("messages", messages);
		
		//Prepare the current date (could do this just using Oracle commands, but this way it works with MySQL as well)
		java.util.Date currentDatetime = new java.util.Date(System.currentTimeMillis());  
		java.sql.Timestamp timestamp = new java.sql.Timestamp(currentDatetime.getTime());
		
		//Get all the POSTed variables
		User user = new User(
				(request.getParameter("username")).trim(), 
				(request.getParameter("password")).trim(), 
				(request.getParameter("userclass")),
				timestamp, 
				(request.getParameter("first_name")).trim(), 
				(request.getParameter("last_name")).trim(),
				(request.getParameter("address")).trim(), 
				(request.getParameter("email")).trim(), 
				(request.getParameter("phone")).trim()
			);

		/* Data Validation */
		
		//Check username isn't blank
		if ((user.getUserName()).trim().equals("")) {
			messages.put("new_user_msg", "<span class=\"message validation\">Username is required..</span>");
		}
		
		//Check password isn't blank
		if ((user.getPassword()).trim().equals("")) {
			messages.put("new_user_msg", "<span class=\"message validation\">Password is required..</span>");
		}
		
		if (messages.size() > 0) {
			request.getRequestDispatcher("admin.jsp").forward(request, response);	
			return;				
		}
		
		
		DBConnector dbConnect = new DBConnector();
		SecurityQueries security = null;
		
		try {
			security = new SecurityQueries(dbConnect.getConnection());
			UserManagementQueries umq = new UserManagementQueries(dbConnect.getConnection(), security);
			umq.createUser(user);	
			messages.put("new_user_msg", "<span class=\"message success\">New User Added.</span>");
			request.getRequestDispatcher("UserList").forward(request, response);			
		}
		catch (com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException e) {
			messages.put("new_user_msg", "<span class=\"message validation\">A user with this name already exists Please try a different name.</span>");
			request.getRequestDispatcher("admin.jsp").forward(request, response);		
			e.printStackTrace();			
		} catch (SQLException e) {
			messages.put("new_user_msg", "<span class=\"message error\">User could not be added. Please try again..</span>");
			request.getRequestDispatcher("admin.jsp").forward(request, response);	
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			//dbConnect.disconnect();
		}
	}

}
